{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {
    "slideshow": {
     "slide_type": "slide"
    }
   },
   "source": [
    "# Solving Multiple Tasks in a Sequence of Async Chats\n",
    "\n",
    "This notebook showcases how to use the new chat interface of conversational agents in AutoGen: a_initiate_chats, to conduct a series of tasks. Similar to \"notebook/agentchat_microsoft_fabric.ipynb\", this new interface allows one to pass multiple tasks and their corresponding dedicated agents and execute concurrently. Depending on the prerequisite task(s), the tasks will be solved concurrently, with the summaries from prerequisite task(s) provided to subsequent tasks as context, if the `summary_method` argument is specified.\n",
    "\n",
    "\\:\\:\\:info Requirements\n",
    "\n",
    "Install `pyautogen`:\n",
    "```bash\n",
    "pip install pyautogen\n",
    "```\n",
    "\n",
    "For more information, please refer to the [installation guide](/docs/installation/).\n",
    "\n",
    "\\:\\:\\:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "import autogen\n",
    "\n",
    "config_list = autogen.config_list_from_json(env_or_file=\"OAI_CONFIG_LIST\")\n",
    "llm_config = {\"config_list\": config_list}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\\:\\:\\:tip\n",
    "\n",
    "Learn more about the various ways to configure LLM endpoints [here](/docs/topics/llm_configuration).\n",
    "\n",
    "\\:\\:\\:"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Example Tasks\n",
    "Below are four example tasks, with each task being a string of text describing the request. The completion of later tasks requires or benefits from the results of prerequisite tasks.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "financial_tasks = [\n",
    "    \"\"\"What are the current stock prices of NVDA and TESLA, and how is the performance over the past month in terms of percentage change?\"\"\",\n",
    "    \"\"\"Investigate possible reasons of the stock performance.\"\"\",\n",
    "    \"\"\"Plot a graph comparing the stock prices over the past month.\"\"\",\n",
    "]\n",
    "\n",
    "writing_tasks = [\"\"\"Develop an engaging blog post using any information provided.\"\"\"]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Scenario 1: Solve the tasks with a series of chats\n",
    "\n",
    "The `initiate_chats` interface can take a list of dictionaries as inputs. Each dictionary preserves the following fields: \n",
    "- `message`: is a string of text (typically a message containing the task);\n",
    "- `recipient`: a conversable agent dedicated for the task;\n",
    "- `summary_method`: A string specifying the method to get a summary from the chat. Currently supported choices include `last_msg`, which takes the last message from the chat history as the summary, and `reflection_with_llm`, which uses an LLM call to reflect on the chat history and summarize a takeaway;\n",
    "- `summary_prompt`: A string specifying how to instruct an LLM-backed agent (either the recipient or the sender in the chat) to reflect on the chat history and derive a summary. If not otherwise specified, a default prompt will be used when `summary_method` is `reflection_with_llm`.\n",
    "\"Summarize the takeaway from the conversation. Do not add any introductory phrases. If the intended request is NOT properly addressed, please point it out.\"\n",
    "- `carryover`: A string or a list of string to specify additional context to be used in the chat. With `initiate_chats`, summary from previous chats will be added as carryover. They will be appended after the carryover provided by the user."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "financial_assistant = autogen.AssistantAgent(\n",
    "    name=\"Financial_assistant\",\n",
    "    llm_config=llm_config,\n",
    ")\n",
    "research_assistant = autogen.AssistantAgent(\n",
    "    name=\"Researcher\",\n",
    "    llm_config=llm_config,\n",
    ")\n",
    "writer = autogen.AssistantAgent(\n",
    "    name=\"writer\",\n",
    "    llm_config=llm_config,\n",
    "    system_message=\"\"\"\n",
    "        You are a professional writer, known for\n",
    "        your insightful and engaging articles.\n",
    "        You transform complex concepts into compelling narratives.\n",
    "        Reply \"TERMINATE\" in the end when everything is done.\n",
    "        \"\"\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "What are the current stock prices of NVDA and TESLA, and how is the performance over the past month in terms of percentage change?\n",
      "\n",
      "With the following carryover: \n",
      "\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "What are the current stock prices of NVDA and TESLA, and how is the performance over the past month in terms of percentage change?\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "To fetch live stock data, we can make use of the \"yfinance\" library in Python, which allows us to download stock data from Yahoo Finance.\n",
      "\n",
      "Install \"yfinance\" by executing the following Python code:\n",
      "\n",
      "```python\n",
      "!pip install yfinance\n",
      "```\n",
      "\n",
      "Then, get the current stock prices and compute the performance over the past month using the following code:\n",
      "\n",
      "```python\n",
      "import yfinance as yf\n",
      "from datetime import datetime, timedelta\n",
      "\n",
      "# Define the ticker symbols\n",
      "tickers = ['NVDA', 'TSLA']\n",
      "\n",
      "# Get today's date\n",
      "today = datetime.today().strftime('%Y-%m-%d')\n",
      "\n",
      "# Get the date one month ago\n",
      "one_month_ago = (datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d')\n",
      "\n",
      "# Initialize a dictionary to store the data\n",
      "data = {}\n",
      "\n",
      "# Loop through the ticker symbols\n",
      "for ticker in tickers:\n",
      "    # Get the historical data for the past month\n",
      "    historical_data = yf.download(ticker, start=one_month_ago, end=today)\n",
      "\n",
      "    # Get the most recent data (today's data)\n",
      "    today_data = historical_data.tail(1)\n",
      "\n",
      "    # Get the earliest data (one month ago's data)\n",
      "    one_month_ago_data = historical_data.head(1)\n",
      "\n",
      "    # Calculate the percentage change over the past month\n",
      "    percentage_change = ((today_data['Close'].iloc[0] - one_month_ago_data['Close'].iloc[0]) / one_month_ago_data['Close'].iloc[0]) * 100\n",
      "\n",
      "    # Store the data in the dictionary\n",
      "    data[ticker] = {\n",
      "        'Current Stock Price': today_data['Close'].iloc[0],\n",
      "        'Performance Over Past Month (%)': percentage_change\n",
      "    }\n",
      "\n",
      "# Print the data\n",
      "for ticker, d in data.items():\n",
      "    print(f\"{ticker}:\")\n",
      "    print(f\"\\tCurrent Stock Price: ${d['Current Stock Price']:.2f}\")\n",
      "    print(f\"\\tPerformance Over Past Month (%): {d['Performance Over Past Month (%)']:.2f}%\")\n",
      "```\n",
      "\n",
      "This Python script retrieves the historical data for the past month for each ticker symbol, calculates the percentage change in stock price over the past month, and prints out the current stock price and the performance over the past month.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "exitcode: 1 (execution failed)\n",
      "Code output: \n",
      "  File \"\", line 1\n",
      "    !pip install yfinance\n",
      "    ^\n",
      "SyntaxError: invalid syntax\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "I apologize for the confusion. The \"!\" character is special syntax for Jupyter notebooks. If you are not using a Jupyter notebook for Python execution, the syntax will be invalid. Please replace \"!\" with the proper syntax to install a Python package. \n",
      "\n",
      "If you're running the code directly in a Python environment, you might need to install yfinance using pip from your shell/command line. Here's the correct command:\n",
      "\n",
      "```sh\n",
      "pip install yfinance\n",
      "```\n",
      "\n",
      "After you've installed the package, you can proceed with the Python code block provided previously to fetch the data.\n",
      "\n",
      "Sorry for the misunderstanding, and thank you for pointing it out.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is sh)...\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: \n",
      "Defaulting to user installation because normal site-packages is not writeable\n",
      "Requirement already satisfied: yfinance in /home/autogen/.local/lib/python3.11/site-packages (0.2.36)\n",
      "Requirement already satisfied: pandas>=1.3.0 in /home/autogen/.local/lib/python3.11/site-packages (from yfinance) (2.2.0)\n",
      "Requirement already satisfied: numpy>=1.16.5 in /usr/local/lib/python3.11/site-packages (from yfinance) (1.26.4)\n",
      "Requirement already satisfied: requests>=2.31 in /usr/local/lib/python3.11/site-packages (from yfinance) (2.31.0)\n",
      "Requirement already satisfied: multitasking>=0.0.7 in /home/autogen/.local/lib/python3.11/site-packages (from yfinance) (0.0.11)\n",
      "Requirement already satisfied: lxml>=4.9.1 in /home/autogen/.local/lib/python3.11/site-packages (from yfinance) (5.1.0)\n",
      "Requirement already satisfied: appdirs>=1.4.4 in /home/autogen/.local/lib/python3.11/site-packages (from yfinance) (1.4.4)\n",
      "Requirement already satisfied: pytz>=2022.5 in /home/autogen/.local/lib/python3.11/site-packages (from yfinance) (2024.1)\n",
      "Requirement already satisfied: frozendict>=2.3.4 in /home/autogen/.local/lib/python3.11/site-packages (from yfinance) (2.4.0)\n",
      "Requirement already satisfied: peewee>=3.16.2 in /home/autogen/.local/lib/python3.11/site-packages (from yfinance) (3.17.1)\n",
      "Requirement already satisfied: beautifulsoup4>=4.11.1 in /usr/local/lib/python3.11/site-packages (from yfinance) (4.12.3)\n",
      "Requirement already satisfied: html5lib>=1.1 in /home/autogen/.local/lib/python3.11/site-packages (from yfinance) (1.1)\n",
      "Requirement already satisfied: soupsieve>1.2 in /usr/local/lib/python3.11/site-packages (from beautifulsoup4>=4.11.1->yfinance) (2.5)\n",
      "Requirement already satisfied: six>=1.9 in /usr/local/lib/python3.11/site-packages (from html5lib>=1.1->yfinance) (1.16.0)\n",
      "Requirement already satisfied: webencodings in /usr/local/lib/python3.11/site-packages (from html5lib>=1.1->yfinance) (0.5.1)\n",
      "Requirement already satisfied: python-dateutil>=2.8.2 in /usr/local/lib/python3.11/site-packages (from pandas>=1.3.0->yfinance) (2.8.2)\n",
      "Requirement already satisfied: tzdata>=2022.7 in /home/autogen/.local/lib/python3.11/site-packages (from pandas>=1.3.0->yfinance) (2024.1)\n",
      "Requirement already satisfied: charset-normalizer<4,>=2 in /usr/local/lib/python3.11/site-packages (from requests>=2.31->yfinance) (3.3.2)\n",
      "Requirement already satisfied: idna<4,>=2.5 in /usr/local/lib/python3.11/site-packages (from requests>=2.31->yfinance) (3.6)\n",
      "Requirement already satisfied: urllib3<3,>=1.21.1 in /home/autogen/.local/lib/python3.11/site-packages (from requests>=2.31->yfinance) (1.26.18)\n",
      "Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.11/site-packages (from requests>=2.31->yfinance) (2024.2.2)\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "Great! Now that the yfinance package is properly installed, we can proceed to fetch the data.\n",
      "\n",
      "Please execute the Python code as shown below:\n",
      "\n",
      "```python\n",
      "import yfinance as yf\n",
      "from datetime import datetime, timedelta\n",
      "\n",
      "# Define the ticker symbols\n",
      "tickers = ['NVDA', 'TSLA']\n",
      "\n",
      "# Get today's date\n",
      "today = datetime.today().strftime('%Y-%m-%d')\n",
      "\n",
      "# Get the date one month ago\n",
      "one_month_ago = (datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d')\n",
      "\n",
      "# Initialize a dictionary to store the data\n",
      "data = {}\n",
      "\n",
      "# Loop through the ticker symbols\n",
      "for ticker in tickers:\n",
      "    # Get the historical data for the past month\n",
      "    historical_data = yf.download(ticker, start=one_month_ago, end=today)\n",
      "\n",
      "    # Get the most recent data (today's data)\n",
      "    today_data = historical_data.tail(1)\n",
      "\n",
      "    # Get the earliest data (one month ago's data)\n",
      "    one_month_ago_data = historical_data.head(1)\n",
      "\n",
      "    # Calculate the percentage change over the past month\n",
      "    percentage_change = ((today_data['Close'].iloc[0] - one_month_ago_data['Close'].iloc[0]) / one_month_ago_data['Close'].iloc[0]) * 100\n",
      "\n",
      "    # Store the data in the dictionary\n",
      "    data[ticker] = {\n",
      "        'Current Stock Price': today_data['Close'].iloc[0],\n",
      "        'Performance Over Past Month (%)': percentage_change\n",
      "    }\n",
      "\n",
      "# Print the data\n",
      "for ticker, d in data.items():\n",
      "    print(f\"{ticker}:\")\n",
      "    print(f\"\\tCurrent Stock Price: ${d['Current Stock Price']:.2f}\")\n",
      "    print(f\"\\tPerformance Over Past Month (%): {d['Performance Over Past Month (%)']:.2f}%\")\n",
      "```\n",
      "\n",
      "This script fetches the current stock prices for NVDA and TSLA and the performance over the past one month in terms of percentage change.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: \n",
      "NVDA:\n",
      "\tCurrent Stock Price: $726.13\n",
      "\tPerformance Over Past Month (%): 21.72%\n",
      "TSLA:\n",
      "\tCurrent Stock Price: $199.95\n",
      "\tPerformance Over Past Month (%): -4.24%\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "Great! Here are the results:\n",
      "\n",
      "- NVDA: \n",
      "  - Current Stock Price: $726.13\n",
      "  - Performance Over Past Month (%): 21.72%\n",
      "\n",
      "- TSLA:\n",
      "  - Current Stock Price: $199.95\n",
      "  - Performance Over Past Month (%): -4.24%\n",
      "\n",
      "Over the past month, the stock price of NVDA increased by 21.72%, while the stock price of TSLA decreased by 4.24%.\n",
      "   \n",
      "Please note that stock prices are subject to market changes and the output values from when you ran this script.\n",
      "\n",
      "If you have any other tasks or need further assistance, please feel free to ask. \n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "Investigate possible reasons of the stock performance.\n",
      "\n",
      "With the following carryover: \n",
      "The NVDA current stock price is $726.13, and the percentage change over the past month is an increase of 21.72%. The TSLA current stock price is $199.95, with a decrease of 4.24% over the past month.\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is Shell)...\u001b[0m\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "Plot a graph comparing the stock prices over the past month.\n",
      "\n",
      "With the following carryover: \n",
      "The NVDA current stock price is $726.13, and the percentage change over the past month is an increase of 21.72%. The TSLA current stock price is $199.95, with a decrease of 4.24% over the past month.\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "Plot a graph comparing the stock prices over the past month.\n",
      "Context: \n",
      "The NVDA current stock price is $726.13, and the percentage change over the past month is an increase of 21.72%. The TSLA current stock price is $199.95, with a decrease of 4.24% over the past month.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "To complete this task, we need historical stock price data for NVDA and TSLA for the past month. However, as I cannot browse the web or fetch live data directly, let's simulate this by inferring the past month's data based on the provided information.\n",
      "\n",
      "We have the current stock price and the percentage change for NVDA and TSLA over the past month. We can calculate the stock price one month ago by reversing the percentage change calculation. \n",
      "\n",
      "Let's also assume for the sake of this task that the stock prices changed linearly over the past month. In reality, stock prices fluctuate daily, so the graph would be more complex, but we can't recreate those fluctuations with just two data points. \n",
      "\n",
      "We can use the `matplotlib` library in Python to plot this data. Please execute the following Python code:\n",
      "\n",
      "```python\n",
      "import matplotlib.pyplot as plt\n",
      "import numpy as np\n",
      "\n",
      "# Current prices and percentage changes\n",
      "NVDA_current_price = 726.13\n",
      "NVDA_change_pct = 21.72\n",
      "TSLA_current_price = 199.95\n",
      "TSLA_change_pct = -4.24\n",
      "\n",
      "# Calculate prices one month ago\n",
      "NVDA_price_month_ago = NVDA_current_price / (1 + NVDA_change_pct/100)\n",
      "TSLA_price_month_ago = TSLA_current_price / (1 - TSLA_change_pct/100)\n",
      "\n",
      "# Create arrays for plotting\n",
      "dates = np.array(['One month ago', 'Today'])\n",
      "NVDA_prices = np.array([NVDA_price_month_ago, NVDA_current_price])\n",
      "TSLA_prices = np.array([TSLA_price_month_ago, TSLA_current_price])\n",
      "\n",
      "# Plotting\n",
      "plt.plot(dates, NVDA_prices, label='NVDA')\n",
      "plt.plot(dates, TSLA_prices, label='TSLA')\n",
      "plt.legend()\n",
      "plt.ylabel('Stock price')\n",
      "plt.title('Stock prices over the past month')\n",
      "plt.show()\n",
      "```\n",
      "\n",
      "This script plots the \"past\" and current stock prices for NVDA and TSLA. It creates a line graph with the date on the x-axis and the stock price on the y-axis. It also adds a title to the graph and a legend indicating which line corresponds to which stock.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: \n",
      "Figure(640x480)\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "Great! The code ran successfully. The `Figure(640x480)` statement denotes the size of the displayed figure, but it's not the actual graph. \n",
      "\n",
      "In a typical interactive Python environment, the `plt.show()` function directly displays the plot. Since the execution environment here may not support interactive display of the graph, you're not seeing the graph as an output. \n",
      "\n",
      "You'd usually see a line chart with two lines, one for NVDA and one for TSLA, indicating their price change from one month ago to today.\n",
      "\n",
      "Sorry for the inconvenience caused by the visualization constraints of the current interaction mode. You can try running the exact same code in an interactive Python environment like Jupyter Notebook or Google Colab, and you would be able to see the graph.\n",
      "\n",
      "I hope you found my assistance helpful in understanding the logic and code to plot the stock prices of NVDA and TSLA. If you have any further questions or tasks, feel free to ask. \n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "Develop an engaging blog post using any information provided.\n",
      "\n",
      "With the following carryover: \n",
      "The NVDA current stock price is $726.13, and the percentage change over the past month is an increase of 21.72%. The TSLA current stock price is $199.95, with a decrease of 4.24% over the past month.\n",
      "There's been a recent increase in NVDA's stock performance and a decrease in TSLA's. The AI provided a script that fetches news headlines about these stocks to understand their performance. Based on the fetched headlines, some factors driving NVDA's stock increase could include imminent earnings reports and a debate about the company's value. The decrease in TSLA stock price could potentially be linked to uncertainties or confusions about its valuation. However, these interpretations are based only on a limited number of news headlines, and other recent events not covered by these headlines could also be influencing the stocks' performance.\n",
      "The assistant provided a detailed way to create a mock graph comparing the stock prices of NVDA and TSLA over the past month, given the current prices and percentage changes. However, due to the assistant's inability to browse the web or fetch live data, and the current platform's inability to display plots, the final graph couldn't be shown. The assistant suggested running the provided Python code in an interactive Python environment like Jupyter Notebook or Google Colab to visualize the graph properly.\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to writer):\n",
      "\n",
      "Develop an engaging blog post using any information provided.\n",
      "Context: \n",
      "The NVDA current stock price is $726.13, and the percentage change over the past month is an increase of 21.72%. The TSLA current stock price is $199.95, with a decrease of 4.24% over the past month.\n",
      "There's been a recent increase in NVDA's stock performance and a decrease in TSLA's. The AI provided a script that fetches news headlines about these stocks to understand their performance. Based on the fetched headlines, some factors driving NVDA's stock increase could include imminent earnings reports and a debate about the company's value. The decrease in TSLA stock price could potentially be linked to uncertainties or confusions about its valuation. However, these interpretations are based only on a limited number of news headlines, and other recent events not covered by these headlines could also be influencing the stocks' performance.\n",
      "The assistant provided a detailed way to create a mock graph comparing the stock prices of NVDA and TSLA over the past month, given the current prices and percentage changes. However, due to the assistant's inability to browse the web or fetch live data, and the current platform's inability to display plots, the final graph couldn't be shown. The assistant suggested running the provided Python code in an interactive Python environment like Jupyter Notebook or Google Colab to visualize the graph properly.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mwriter\u001b[0m (to User):\n",
      "\n",
      "Title: Navigating the Highs and Lows: A Tale of Two Stocks- NVDA and TSLA\n",
      "\n",
      "If you've been tracking the stock market recently, you might have noticed some significant activity involving two household names. These tech juggernauts- NVIDIA Corp (NVDA) and Tesla Inc (TSLA), have experienced significantly contrasting fortunes over the past month. \n",
      "\n",
      "As of now, the NVDA stock price stands at a lofty $726.13, soaring an astonishing 21.72% in the past month. TSLA, however, has had a bumpier ride, with the current price of $199.95 reflecting a 4.24% decrease during the same period. \n",
      "\n",
      "What's driving the surging ascent of NVDA and the faltering trajectory of TSLA, you might ask? Well, sometimes the answers can be found in the daily news cycle.\n",
      "\n",
      "According to news headlines fetched by our AI assistant, NVDA's recent skyrocket can potentially be linked to events like imminent earnings reports and a burgeoning debate around the company's value. These factors have managed to cast a positive light on the company. Investors may perceive them as indicators of a prospective growth, triggering increased stock purchases. \n",
      "\n",
      "Yet, every coin has two sides. For TSLA, recent news may have spread more confusion and uncertainty than confidence. Headlines pointing to ambiguities about the company's valuation have clouded its fiscal outlook, leading to a softening of the stock price. \n",
      "\n",
      "Before attaching too much weight to these possibilities, it's essential to highlight that news headlines offers just a fraction of the full picture. The market's pulse is influenced by a plethora of factors, with many taking place behind headlines. Hence, while headlines undeniably play a role in influencing stock performance, they should be only part of any comprehensive market analysis.\n",
      "\n",
      "To provide a deeper understanding of these stock trajectories, our AI helper put forth a detailed method to mock up a comparative graph of NVDA and TSLA prices over the past month. However, our current environment lacks the capability for web browsing or live data fetching, so the visualization isn’t available in this post. For those keen to see the graphical view, we recommend inputting the provided Python code into an interactive Python environment like Jupyter Notebook or Google Colab.\n",
      "\n",
      "Whether you're an experienced trader or a budding market enthusiast, understanding the forces moving major stocks like NVDA and TSLA can give you valuable insight into the tech industry's overall health and future direction. So, keep those news alerts on, keep questioning, and keep connecting the dots.\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "user = autogen.UserProxyAgent(\n",
    "    name=\"User\",\n",
    "    human_input_mode=\"NEVER\",\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
    "    code_execution_config={\n",
    "        \"last_n_messages\": 1,\n",
    "        \"work_dir\": \"tasks\",\n",
    "        \"use_docker\": False,\n",
    "    },  # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.\n",
    ")\n",
    "\n",
    "chat_results = await user.a_initiate_chats(  # noqa: F704\n",
    "    [\n",
    "        {\n",
    "            \"chat_id\": 1,\n",
    "            \"recipient\": financial_assistant,\n",
    "            \"message\": financial_tasks[0],\n",
    "            \"silent\": False,\n",
    "            \"summary_method\": \"reflection_with_llm\",\n",
    "        },\n",
    "        {\n",
    "            \"chat_id\": 2,\n",
    "            \"prerequisites\": [1],\n",
    "            \"recipient\": research_assistant,\n",
    "            \"message\": financial_tasks[1],\n",
    "            \"silent\": True,\n",
    "            \"summary_method\": \"reflection_with_llm\",\n",
    "        },\n",
    "        {\n",
    "            \"chat_id\": 3,\n",
    "            \"prerequisites\": [1],\n",
    "            \"recipient\": financial_assistant,\n",
    "            \"message\": financial_tasks[2],\n",
    "            \"silent\": False,\n",
    "            \"summary_method\": \"reflection_with_llm\",\n",
    "        },\n",
    "        {\"chat_id\": 4, \"prerequisites\": [1, 2, 3], \"recipient\": writer, \"message\": writing_tasks[0]},\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Check chat results\n",
    "The `initiate_chat` method returns a `ChatResult` object, which is a dataclass object storing information about the chat. Currently, it includes the following attributes:\n",
    "\n",
    "- `chat_history`: a list of chat history.\n",
    "- `summary`: a string of chat summary. A summary is only available if a summary_method is provided when initiating the chat.\n",
    "- `cost`: a tuple of (total_cost, total_actual_cost), where total_cost is a dictionary of cost information, and total_actual_cost is a dictionary of information on the actual incurred cost with cache.\n",
    "- `human_input`: a list of strings of human inputs solicited during the chat. (Note that since we are setting `human_input_mode` to `NEVER` in this notebook, this list is always empty.)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "*****1th chat*******:\n",
      "The NVDA current stock price is $726.13, and the percentage change over the past month is an increase of 21.72%. The TSLA current stock price is $199.95, with a decrease of 4.24% over the past month.\n",
      "Human input in the middle: []\n",
      "Conversation cost:  ({'total_cost': 0.9493499999999998, 'gpt-4-0613': {'cost': 0.9493499999999998, 'prompt_tokens': 22291, 'completion_tokens': 4677, 'total_tokens': 26968}}, {'total_cost': 0.26868, 'gpt-4-0613': {'cost': 0.26868, 'prompt_tokens': 5408, 'completion_tokens': 1774, 'total_tokens': 7182}})\n",
      "\n",
      "\n",
      "\n",
      "*****2th chat*******:\n",
      "There's been a recent increase in NVDA's stock performance and a decrease in TSLA's. The AI provided a script that fetches news headlines about these stocks to understand their performance. Based on the fetched headlines, some factors driving NVDA's stock increase could include imminent earnings reports and a debate about the company's value. The decrease in TSLA stock price could potentially be linked to uncertainties or confusions about its valuation. However, these interpretations are based only on a limited number of news headlines, and other recent events not covered by these headlines could also be influencing the stocks' performance.\n",
      "Human input in the middle: []\n",
      "Conversation cost:  ({'total_cost': 0.58845, 'gpt-4-0613': {'cost': 0.58845, 'prompt_tokens': 12177, 'completion_tokens': 3719, 'total_tokens': 15896}}, {'total_cost': 0.36668999999999996, 'gpt-4-0613': {'cost': 0.36668999999999996, 'prompt_tokens': 8801, 'completion_tokens': 1711, 'total_tokens': 10512}})\n",
      "\n",
      "\n",
      "\n",
      "*****3th chat*******:\n",
      "The assistant provided a detailed way to create a mock graph comparing the stock prices of NVDA and TSLA over the past month, given the current prices and percentage changes. However, due to the assistant's inability to browse the web or fetch live data, and the current platform's inability to display plots, the final graph couldn't be shown. The assistant suggested running the provided Python code in an interactive Python environment like Jupyter Notebook or Google Colab to visualize the graph properly.\n",
      "Human input in the middle: []\n",
      "Conversation cost:  ({'total_cost': 1.0658699999999997, 'gpt-4-0613': {'cost': 1.0658699999999997, 'prompt_tokens': 24657, 'completion_tokens': 5436, 'total_tokens': 30093}}, {'total_cost': 0.26868, 'gpt-4-0613': {'cost': 0.26868, 'prompt_tokens': 5408, 'completion_tokens': 1774, 'total_tokens': 7182}})\n",
      "\n",
      "\n",
      "\n",
      "*****4th chat*******:\n",
      "Title: Navigating the Highs and Lows: A Tale of Two Stocks- NVDA and TSLA\n",
      "\n",
      "If you've been tracking the stock market recently, you might have noticed some significant activity involving two household names. These tech juggernauts- NVIDIA Corp (NVDA) and Tesla Inc (TSLA), have experienced significantly contrasting fortunes over the past month. \n",
      "\n",
      "As of now, the NVDA stock price stands at a lofty $726.13, soaring an astonishing 21.72% in the past month. TSLA, however, has had a bumpier ride, with the current price of $199.95 reflecting a 4.24% decrease during the same period. \n",
      "\n",
      "What's driving the surging ascent of NVDA and the faltering trajectory of TSLA, you might ask? Well, sometimes the answers can be found in the daily news cycle.\n",
      "\n",
      "According to news headlines fetched by our AI assistant, NVDA's recent skyrocket can potentially be linked to events like imminent earnings reports and a burgeoning debate around the company's value. These factors have managed to cast a positive light on the company. Investors may perceive them as indicators of a prospective growth, triggering increased stock purchases. \n",
      "\n",
      "Yet, every coin has two sides. For TSLA, recent news may have spread more confusion and uncertainty than confidence. Headlines pointing to ambiguities about the company's valuation have clouded its fiscal outlook, leading to a softening of the stock price. \n",
      "\n",
      "Before attaching too much weight to these possibilities, it's essential to highlight that news headlines offers just a fraction of the full picture. The market's pulse is influenced by a plethora of factors, with many taking place behind headlines. Hence, while headlines undeniably play a role in influencing stock performance, they should be only part of any comprehensive market analysis.\n",
      "\n",
      "To provide a deeper understanding of these stock trajectories, our AI helper put forth a detailed method to mock up a comparative graph of NVDA and TSLA prices over the past month. However, our current environment lacks the capability for web browsing or live data fetching, so the visualization isn’t available in this post. For those keen to see the graphical view, we recommend inputting the provided Python code into an interactive Python environment like Jupyter Notebook or Google Colab.\n",
      "\n",
      "Whether you're an experienced trader or a budding market enthusiast, understanding the forces moving major stocks like NVDA and TSLA can give you valuable insight into the tech industry's overall health and future direction. So, keep those news alerts on, keep questioning, and keep connecting the dots.\n",
      "\n",
      "\n",
      "Human input in the middle: []\n",
      "Conversation cost:  ({'total_cost': 0.13599, 'gpt-4-0613': {'cost': 0.13599, 'prompt_tokens': 1043, 'completion_tokens': 1745, 'total_tokens': 2788}}, {'total_cost': 0.13599, 'gpt-4-0613': {'cost': 0.13599, 'prompt_tokens': 1043, 'completion_tokens': 1745, 'total_tokens': 2788}})\n",
      "\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for i, chat_res in chat_results.items():\n",
    "    print(f\"*****{i}th chat*******:\")\n",
    "    print(chat_res.summary)\n",
    "    print(\"Human input in the middle:\", chat_res.human_input)\n",
    "    print(\"Conversation cost: \", chat_res.cost)\n",
    "    print(\"\\n\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Scenario 2: With human inputs revising tasks in the middle\n",
    "\n",
    "Since AutoGen agents support soliciting human inputs during a chat if `human_input_mode` is specificed properly, the actual task might be revised in the middle of a chat. \n",
    "\n",
    "The example below showcases that even if a task is revised in the middle (for the first task, the human user requests to get Microsoft's stock price information as well, in addition to NVDA and TSLA), the `reflection_with_llm`` summary method can still capture it, as it reflects on the whole conversation instead of just the original request."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "What are the current stock prices of NVDA and TESLA, and how is the performance over the past month in terms of percentage change?\n",
      "\n",
      "With the following carryover: \n",
      "\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "What are the current stock prices of NVDA and TESLA, and how is the performance over the past month in terms of percentage change?\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "To fetch live stock data, we can make use of the \"yfinance\" library in Python, which allows us to download stock data from Yahoo Finance.\n",
      "\n",
      "Install \"yfinance\" by executing the following Python code:\n",
      "\n",
      "```python\n",
      "!pip install yfinance\n",
      "```\n",
      "\n",
      "Then, get the current stock prices and compute the performance over the past month using the following code:\n",
      "\n",
      "```python\n",
      "import yfinance as yf\n",
      "from datetime import datetime, timedelta\n",
      "\n",
      "# Define the ticker symbols\n",
      "tickers = ['NVDA', 'TSLA']\n",
      "\n",
      "# Get today's date\n",
      "today = datetime.today().strftime('%Y-%m-%d')\n",
      "\n",
      "# Get the date one month ago\n",
      "one_month_ago = (datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d')\n",
      "\n",
      "# Initialize a dictionary to store the data\n",
      "data = {}\n",
      "\n",
      "# Loop through the ticker symbols\n",
      "for ticker in tickers:\n",
      "    # Get the historical data for the past month\n",
      "    historical_data = yf.download(ticker, start=one_month_ago, end=today)\n",
      "\n",
      "    # Get the most recent data (today's data)\n",
      "    today_data = historical_data.tail(1)\n",
      "\n",
      "    # Get the earliest data (one month ago's data)\n",
      "    one_month_ago_data = historical_data.head(1)\n",
      "\n",
      "    # Calculate the percentage change over the past month\n",
      "    percentage_change = ((today_data['Close'].iloc[0] - one_month_ago_data['Close'].iloc[0]) / one_month_ago_data['Close'].iloc[0]) * 100\n",
      "\n",
      "    # Store the data in the dictionary\n",
      "    data[ticker] = {\n",
      "        'Current Stock Price': today_data['Close'].iloc[0],\n",
      "        'Performance Over Past Month (%)': percentage_change\n",
      "    }\n",
      "\n",
      "# Print the data\n",
      "for ticker, d in data.items():\n",
      "    print(f\"{ticker}:\")\n",
      "    print(f\"\\tCurrent Stock Price: ${d['Current Stock Price']:.2f}\")\n",
      "    print(f\"\\tPerformance Over Past Month (%): {d['Performance Over Past Month (%)']:.2f}%\")\n",
      "```\n",
      "\n",
      "This Python script retrieves the historical data for the past month for each ticker symbol, calculates the percentage change in stock price over the past month, and prints out the current stock price and the performance over the past month.\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/workspaces/autogen/autogen/agentchat/chat.py:46: UserWarning: Repetitive recipients detected: The chat history will be cleared by default if a recipient appears more than once. To retain the chat history, please set 'clear_history=False' in the configuration of the repeating agent.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "Pls add Microsoft information as well.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "Sure, let's add Microsoft (MSFT) to the list of tickers. Here's the updated Python code:\n",
      "\n",
      "```python\n",
      "import yfinance as yf\n",
      "from datetime import datetime, timedelta\n",
      "\n",
      "# Define the ticker symbols\n",
      "tickers = ['NVDA', 'TSLA', 'MSFT']\n",
      "\n",
      "# Get today's date\n",
      "today = datetime.today().strftime('%Y-%m-%d')\n",
      "\n",
      "# Get the date one month ago\n",
      "one_month_ago = (datetime.today() - timedelta(days=30)).strftime('%Y-%m-%d')\n",
      "\n",
      "# Initialize a dictionary to store the data\n",
      "data = {}\n",
      "\n",
      "# Loop through the ticker symbols\n",
      "for ticker in tickers:\n",
      "    # Get the historical data for the past month\n",
      "    historical_data = yf.download(ticker, start=one_month_ago, end=today)\n",
      "\n",
      "    # Get the most recent data (today's data)\n",
      "    today_data = historical_data.tail(1)\n",
      "\n",
      "    # Get the earliest data (one month ago's data)\n",
      "    one_month_ago_data = historical_data.head(1)\n",
      "\n",
      "    # Calculate the percentage change over the past month\n",
      "    percentage_change = ((today_data['Close'].iloc[0] - one_month_ago_data['Close'].iloc[0]) / one_month_ago_data['Close'].iloc[0]) * 100\n",
      "\n",
      "    # Store the data in the dictionary\n",
      "    data[ticker] = {\n",
      "        'Current Stock Price': today_data['Close'].iloc[0],\n",
      "        'Performance Over Past Month (%)': percentage_change\n",
      "    }\n",
      "\n",
      "# Print the data\n",
      "for ticker, d in data.items():\n",
      "    print(f\"{ticker}:\")\n",
      "    print(f\"\\tCurrent Stock Price: ${d['Current Stock Price']:.2f}\")\n",
      "    print(f\"\\tPerformance Over Past Month (%): {d['Performance Over Past Month (%)']:.2f}%\")\n",
      "```\n",
      "\n",
      "This is essentially the same script as before, but now it also fetches and processes stock data for Microsoft.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "Investigate possible reasons of the stock performance.\n",
      "\n",
      "With the following carryover: \n",
      "The assistant provided a Python code to fetch the current stock prices and compute performance over the past month in terms of percentage change for the given stock ticker symbols, NVDA (NVIDIA Corp), TSLA (Tesla Inc), and MSFT (Microsoft Corp). This was done using the yfinance library which fetches the data from Yahoo Finance.\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "Plot a graph comparing the stock prices over the past month.\n",
      "\n",
      "With the following carryover: \n",
      "The assistant provided a Python code to fetch the current stock prices and compute performance over the past month in terms of percentage change for the given stock ticker symbols, NVDA (NVIDIA Corp), TSLA (Tesla Inc), and MSFT (Microsoft Corp). This was done using the yfinance library which fetches the data from Yahoo Finance.\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Financial_assistant):\n",
      "\n",
      "Plot a graph comparing the stock prices over the past month.\n",
      "Context: \n",
      "The assistant provided a Python code to fetch the current stock prices and compute performance over the past month in terms of percentage change for the given stock ticker symbols, NVDA (NVIDIA Corp), TSLA (Tesla Inc), and MSFT (Microsoft Corp). This was done using the yfinance library which fetches the data from Yahoo Finance.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mFinancial_assistant\u001b[0m (to User):\n",
      "\n",
      "Great, I will create a Python script to download historical data for these stocks and plot a comparison graph using libraries such as pandas, yfinance and matplotlib for data handling, financial data fetching and plotting, respectively.\n",
      "\n",
      "```python\n",
      "# filename: stock_price_comparison.py\n",
      "\n",
      "import yfinance as yf\n",
      "import matplotlib.pyplot as plt\n",
      "import pandas as pd\n",
      "from pandas.plotting import register_matplotlib_converters\n",
      "register_matplotlib_converters()\n",
      "\n",
      "# define the ticker symbol\n",
      "ticker_list = ['NVDA', 'TSLA', 'MSFT']\n",
      "\n",
      "# create empty dataframe\n",
      "stock_data = pd.DataFrame()\n",
      "\n",
      "# Fetch the data\n",
      "for ticker in ticker_list: \n",
      "    stock = yf.Ticker(ticker)\n",
      "    temp = stock.history(period='1mo')\n",
      "    temp.reset_index(level=0, inplace=True)\n",
      "    temp['Ticker'] = ticker\n",
      "    stock_data = stock_data.append(temp)\n",
      "\n",
      "# Save each stock's closing price and date to a separate .csv\n",
      "for ticker in ticker_list:\n",
      "    temp = stock_data[stock_data['Ticker'] == ticker]\n",
      "    temp[['Date', 'Close']].to_csv(f'{ticker}_closing_price.csv', index=False)\n",
      "\n",
      "# plot each stock's closing price in one graph\n",
      "plt.figure(figsize=(14, 6))\n",
      "for ticker in ticker_list:\n",
      "    temp = stock_data[stock_data['Ticker'] == ticker]\n",
      "    plt.plot(temp['Date'], temp['Close'], label=ticker)\n",
      "plt.xlabel('Date')\n",
      "plt.ylabel('Close Price')\n",
      "plt.title('Stock Price over Past Month')\n",
      "plt.legend()\n",
      "plt.grid()\n",
      "plt.savefig('stock_price_comparison.png')\n",
      "\n",
      "print(\"Stock price comparison graph saved as 'stock_price_comparison.png'.\")\n",
      "\n",
      "```\n",
      "This script will fetch the stock prices for the past month of the specified companies, then it plots these on the same graph to compare. The graph is saved as a PNG image named \"stock_price_comparison.png\". Each stock's closing price and date data are also saved to a separate .csv file (e.g., \"NVDA_closing_price.csv\"). Please run this script and check the generated graph and files.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "Develop an engaging blog post using any information provided.\n",
      "\n",
      "With the following carryover: \n",
      "The assistant provided a Python code to fetch the current stock prices and compute performance over the past month in terms of percentage change for the given stock ticker symbols, NVDA (NVIDIA Corp), TSLA (Tesla Inc), and MSFT (Microsoft Corp). This was done using the yfinance library which fetches the data from Yahoo Finance.\n",
      "The performance of a company's stock price could be influenced by various factors, including earnings reports, company announcements, market trends, economic indicators, and investor sentiment. To find out why a specific stock performed as it did, look out for any news, announcements, earnings report, or significant events that have occurred in the past month for that stock. Also, check the overall market trends and economic indicators during this period, and try to understand the investor sentiment towards the company. To fetch and analyze news related to a company, use the NewsAPI and Python requests library.\n",
      "The assistant provided a Python code to fetch and compare the stock prices of NVIDIA Corp (NVDA), Tesla Inc (TSLA), and Microsoft Corp (MSFT) from the past month. The code uses the yfinance library to download historical data, pandas to manage the data, and matplotlib to plot the graph. It fetches the stock prices and plots them on a graph with date on the x-axis and closing price on the y-axis. The script saves the graph as a PNG image and the closing price and date of each stock in separate .csv files.\n",
      "\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to writer):\n",
      "\n",
      "Develop an engaging blog post using any information provided.\n",
      "Context: \n",
      "The assistant provided a Python code to fetch the current stock prices and compute performance over the past month in terms of percentage change for the given stock ticker symbols, NVDA (NVIDIA Corp), TSLA (Tesla Inc), and MSFT (Microsoft Corp). This was done using the yfinance library which fetches the data from Yahoo Finance.\n",
      "The performance of a company's stock price could be influenced by various factors, including earnings reports, company announcements, market trends, economic indicators, and investor sentiment. To find out why a specific stock performed as it did, look out for any news, announcements, earnings report, or significant events that have occurred in the past month for that stock. Also, check the overall market trends and economic indicators during this period, and try to understand the investor sentiment towards the company. To fetch and analyze news related to a company, use the NewsAPI and Python requests library.\n",
      "The assistant provided a Python code to fetch and compare the stock prices of NVIDIA Corp (NVDA), Tesla Inc (TSLA), and Microsoft Corp (MSFT) from the past month. The code uses the yfinance library to download historical data, pandas to manage the data, and matplotlib to plot the graph. It fetches the stock prices and plots them on a graph with date on the x-axis and closing price on the y-axis. The script saves the graph as a PNG image and the closing price and date of each stock in separate .csv files.\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mwriter\u001b[0m (to User):\n",
      "\n",
      "# Scripting the Stock Market: A Deeper Look into NVIDIA, Tesla, and Microsoft\n",
      "\n",
      "Imagine being able to chart the highs and lows of your favorite stocks just by running a bit of code. Whether you're a seasoned investor or a curious newbie, understanding stock trends of top-performing companies like NVIDIA Corp (NVDA), Tesla Inc (TSLA), and Microsoft Corp (MSFT) can offer invaluable insights into the fast-paced world of finance. \n",
      "\n",
      "Traditionally, this type of analysis would require countless hours spent poring over dense financial documents, analyzing figures, and making educated guesses. Yet, with Python, the prospect of quickly reviewing stock performances isn't just possible—it's incredibly accessible and surprisingly engaging.\n",
      "\n",
      "## Harnessing Python and Yahoo Finance Data\n",
      "\n",
      "In the world where data reigns supreme, the clever use of Python code makes it a cinch to fetch current stock prices and calculate performance over a given period. The yfinance library proves invaluable here. It fetches data from Yahoo Finance, sparing you the hassle of data collection. \n",
      "\n",
      "With just a Python script, you can instruct your computer to fetch and analyze the last month's performance for NVDA, TSLA, and MSFT in terms of percentage. This simplifies the process of understanding what’s been happening with these dynamite stocks recently. \n",
      "\n",
      "## Unravel the Mystery Behind Stock Performance\n",
      "\n",
      "Of course, knowing a stock's performance is just the first step. Why does a particular stock perform the way it does? There’s not always an easy answer, as stock performance can hinge on various factors. These mandators include company announcements, earnings reports, investor sentiment, market trends, and economic indicators.\n",
      "\n",
      "For those of you hungry to know why NVDA, TSLA, or MSFT experienced a particular spike or dip, consider looking into any significant events, news, or announcements over the past month relating to that stock. Was there a breakthrough product announced? Perhaps a promising earnings report? Or maybe a broader market trend affected technology companies as a whole?\n",
      "\n",
      "## Dive Deeper with the NewsAPI\n",
      "\n",
      "One way to stay afloat in the torrent of stock-related news is by using the NewsAPI in conjunction with the Python requests library. This combination assists in fetching and analyzing news related to the companies of your interest, keeping you abreast of events that might directly affect stock performance.\n",
      "\n",
      "## Visualize the Stock Prices with matplotlib\n",
      "\n",
      "Visualization is an absolute game-changer when it comes to understanding data, and yes, stock prices are no different whatsoever. Once you've fetched the stock prices using yfinance, you can use the Python libraries, pandas for data management and matplotlib for plotting. These tools allow you to graph the stocks' closing prices over the given period, providing a clear, visual summary of their performance. \n",
      "\n",
      "To make the analysis even more concrete, the Python code stores the closing dates and prices of each stock in separate .csv files. This way, you always have a concrete log of the data breaking down the stock performances over time.\n",
      "\n",
      "And there you have it! Using Python, even the novice investors among us can dive headfirst into the sea of stock market analysis. As you get comfortable retrieving and analyzing stock data, you'll find the information you glean from this process invaluable, whether you're making personal investments or just following market trends out of interest.\n",
      "\n",
      "Welcome to the new era of stock analysis! Happy data crunching!\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    }
   ],
   "source": [
    "user = autogen.UserProxyAgent(\n",
    "    name=\"User\",\n",
    "    human_input_mode=\"ALWAYS\",  # ask human for input at each step\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
    "    code_execution_config={\n",
    "        \"last_n_messages\": 1,\n",
    "        \"work_dir\": \"tasks\",\n",
    "        \"use_docker\": False,\n",
    "    },  # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.\n",
    ")\n",
    "\n",
    "chat_results = await user.a_initiate_chats(  # noqa: F704\n",
    "    [\n",
    "        {\n",
    "            \"chat_id\": 1,\n",
    "            \"recipient\": financial_assistant,\n",
    "            \"message\": financial_tasks[0],\n",
    "            \"silent\": False,\n",
    "            \"summary_method\": \"reflection_with_llm\",\n",
    "        },\n",
    "        {\n",
    "            \"chat_id\": 2,\n",
    "            \"prerequisites\": [1],\n",
    "            \"recipient\": research_assistant,\n",
    "            \"message\": financial_tasks[1],\n",
    "            \"silent\": True,\n",
    "            \"summary_method\": \"reflection_with_llm\",\n",
    "        },\n",
    "        {\n",
    "            \"chat_id\": 3,\n",
    "            \"prerequisites\": [1],\n",
    "            \"recipient\": financial_assistant,\n",
    "            \"message\": financial_tasks[2],\n",
    "            \"silent\": False,\n",
    "            \"summary_method\": \"reflection_with_llm\",\n",
    "        },\n",
    "        {\"chat_id\": 4, \"prerequisites\": [1, 2, 3], \"recipient\": writer, \"message\": writing_tasks[0]},\n",
    "    ]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Check chat results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "*****1th chat*******:\n",
      "The assistant provided a Python code to fetch the current stock prices and compute performance over the past month in terms of percentage change for the given stock ticker symbols, NVDA (NVIDIA Corp), TSLA (Tesla Inc), and MSFT (Microsoft Corp). This was done using the yfinance library which fetches the data from Yahoo Finance.\n",
      "Human input in the middle: ['Pls add Microsoft information as well.', 'exit']\n",
      "Conversation cost:  ({'total_cost': 0.56541, 'gpt-4-0613': {'cost': 0.56541, 'prompt_tokens': 13003, 'completion_tokens': 2922, 'total_tokens': 15925}}, {'total_cost': 0.20337, 'gpt-4-0613': {'cost': 0.20337, 'prompt_tokens': 4311, 'completion_tokens': 1234, 'total_tokens': 5545}})\n",
      "\n",
      "\n",
      "\n",
      "*****2th chat*******:\n",
      "The performance of a company's stock price could be influenced by various factors, including earnings reports, company announcements, market trends, economic indicators, and investor sentiment. To find out why a specific stock performed as it did, look out for any news, announcements, earnings report, or significant events that have occurred in the past month for that stock. Also, check the overall market trends and economic indicators during this period, and try to understand the investor sentiment towards the company. To fetch and analyze news related to a company, use the NewsAPI and Python requests library.\n",
      "Human input in the middle: ['exit']\n",
      "Conversation cost:  ({'total_cost': 0.34029, 'gpt-4-0613': {'cost': 0.34029, 'prompt_tokens': 6785, 'completion_tokens': 2279, 'total_tokens': 9064}}, {'total_cost': 0.22940999999999998, 'gpt-4-0613': {'cost': 0.22940999999999998, 'prompt_tokens': 5097, 'completion_tokens': 1275, 'total_tokens': 6372}})\n",
      "\n",
      "\n",
      "\n",
      "*****3th chat*******:\n",
      "The assistant provided a Python code to fetch and compare the stock prices of NVIDIA Corp (NVDA), Tesla Inc (TSLA), and Microsoft Corp (MSFT) from the past month. The code uses the yfinance library to download historical data, pandas to manage the data, and matplotlib to plot the graph. It fetches the stock prices and plots them on a graph with date on the x-axis and closing price on the y-axis. The script saves the graph as a PNG image and the closing price and date of each stock in separate .csv files.\n",
      "\n",
      "Human input in the middle: ['exit']\n",
      "Conversation cost:  ({'total_cost': 0.63072, 'gpt-4-0613': {'cost': 0.63072, 'prompt_tokens': 14100, 'completion_tokens': 3462, 'total_tokens': 17562}}, {'total_cost': 0.26868, 'gpt-4-0613': {'cost': 0.26868, 'prompt_tokens': 5408, 'completion_tokens': 1774, 'total_tokens': 7182}})\n",
      "\n",
      "\n",
      "\n",
      "*****4th chat*******:\n",
      "# Scripting the Stock Market: A Deeper Look into NVIDIA, Tesla, and Microsoft\n",
      "\n",
      "Imagine being able to chart the highs and lows of your favorite stocks just by running a bit of code. Whether you're a seasoned investor or a curious newbie, understanding stock trends of top-performing companies like NVIDIA Corp (NVDA), Tesla Inc (TSLA), and Microsoft Corp (MSFT) can offer invaluable insights into the fast-paced world of finance. \n",
      "\n",
      "Traditionally, this type of analysis would require countless hours spent poring over dense financial documents, analyzing figures, and making educated guesses. Yet, with Python, the prospect of quickly reviewing stock performances isn't just possible—it's incredibly accessible and surprisingly engaging.\n",
      "\n",
      "## Harnessing Python and Yahoo Finance Data\n",
      "\n",
      "In the world where data reigns supreme, the clever use of Python code makes it a cinch to fetch current stock prices and calculate performance over a given period. The yfinance library proves invaluable here. It fetches data from Yahoo Finance, sparing you the hassle of data collection. \n",
      "\n",
      "With just a Python script, you can instruct your computer to fetch and analyze the last month's performance for NVDA, TSLA, and MSFT in terms of percentage. This simplifies the process of understanding what’s been happening with these dynamite stocks recently. \n",
      "\n",
      "## Unravel the Mystery Behind Stock Performance\n",
      "\n",
      "Of course, knowing a stock's performance is just the first step. Why does a particular stock perform the way it does? There’s not always an easy answer, as stock performance can hinge on various factors. These mandators include company announcements, earnings reports, investor sentiment, market trends, and economic indicators.\n",
      "\n",
      "For those of you hungry to know why NVDA, TSLA, or MSFT experienced a particular spike or dip, consider looking into any significant events, news, or announcements over the past month relating to that stock. Was there a breakthrough product announced? Perhaps a promising earnings report? Or maybe a broader market trend affected technology companies as a whole?\n",
      "\n",
      "## Dive Deeper with the NewsAPI\n",
      "\n",
      "One way to stay afloat in the torrent of stock-related news is by using the NewsAPI in conjunction with the Python requests library. This combination assists in fetching and analyzing news related to the companies of your interest, keeping you abreast of events that might directly affect stock performance.\n",
      "\n",
      "## Visualize the Stock Prices with matplotlib\n",
      "\n",
      "Visualization is an absolute game-changer when it comes to understanding data, and yes, stock prices are no different whatsoever. Once you've fetched the stock prices using yfinance, you can use the Python libraries, pandas for data management and matplotlib for plotting. These tools allow you to graph the stocks' closing prices over the given period, providing a clear, visual summary of their performance. \n",
      "\n",
      "To make the analysis even more concrete, the Python code stores the closing dates and prices of each stock in separate .csv files. This way, you always have a concrete log of the data breaking down the stock performances over time.\n",
      "\n",
      "And there you have it! Using Python, even the novice investors among us can dive headfirst into the sea of stock market analysis. As you get comfortable retrieving and analyzing stock data, you'll find the information you glean from this process invaluable, whether you're making personal investments or just following market trends out of interest.\n",
      "\n",
      "Welcome to the new era of stock analysis! Happy data crunching!\n",
      "\n",
      "\n",
      "Human input in the middle: ['exit']\n",
      "Conversation cost:  ({'total_cost': 0.09408, 'gpt-4-0613': {'cost': 0.09408, 'prompt_tokens': 702, 'completion_tokens': 1217, 'total_tokens': 1919}}, {'total_cost': 0.09408, 'gpt-4-0613': {'cost': 0.09408, 'prompt_tokens': 702, 'completion_tokens': 1217, 'total_tokens': 1919}})\n",
      "\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "for i, chat_res in chat_results.items():\n",
    "    print(f\"*****{i}th chat*******:\")\n",
    "    print(chat_res.summary)\n",
    "    print(\"Human input in the middle:\", chat_res.human_input)\n",
    "    print(\"Conversation cost: \", chat_res.cost)\n",
    "    print(\"\\n\\n\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Scenario 3: Solve the tasks with a series of chats involving group chat"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "What are the current stock prices of NVDA and TESLA, and how is the performance over the past month in terms of percentage change?\n",
      "\n",
      "With the following carryover: \n",
      "\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Researcher):\n",
      "\n",
      "What are the current stock prices of NVDA and TESLA, and how is the performance over the past month in terms of percentage change?\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mResearcher\u001b[0m (to User):\n",
      "\n",
      "To obtain the current stock prices of NVDA (Nvidia Corporation) and TSLA (Tesla, Inc.), as well as their performance over the past month in terms of percentage change, I will use Python code to fetch this information from a financial data API. For this task, we can use the Yahoo Finance API through the `yfinance` library, which allows us to collect stock information programmatically.\n",
      "\n",
      "Here is the plan:\n",
      "1. Use Python code to access the required stock data via the `yfinance` library.\n",
      "2. Fetch the current prices of NVDA and TSLA.\n",
      "3. Calculate the percentage change in their stock prices over the past month.\n",
      "\n",
      "First, you'll need to ensure that the `yfinance` library is installed. If it's not already installed, you can install it using pip. Execute the following Python code to perform the tasks:\n",
      "\n",
      "```python\n",
      "# filename: stock_info.py\n",
      "\n",
      "import yfinance as yf\n",
      "from datetime import datetime, timedelta\n",
      "\n",
      "# Define the tickers for Nvidia and Tesla\n",
      "tickers = [\"NVDA\", \"TSLA\"]\n",
      "\n",
      "# Define the time period: end date is today, start date is one month ago\n",
      "end_date = datetime.today()\n",
      "start_date = end_date - timedelta(days=30)\n",
      "\n",
      "# Function to fetch and display stock info\n",
      "def fetch_and_display_info(ticker):\n",
      "    stock = yf.Ticker(ticker)\n",
      "    \n",
      "    # Fetch historical data for the past month\n",
      "    hist = stock.history(start=start_date, end=end_date)\n",
      "    \n",
      "    # Get the last closing price (most recent date)\n",
      "    last_close_price = hist['Close'].iloc[-1]\n",
      "    \n",
      "    # Calculate the percentage change over the past month\n",
      "    start_price = hist['Close'].iloc[0]  # First day's closing price in the hist data\n",
      "    percentage_change = ((last_close_price - start_price) / start_price) * 100\n",
      "    \n",
      "    print(f\"{ticker} Current Price: ${last_close_price:.2f}\")\n",
      "    print(f\"{ticker} Performance Over The Past Month: {percentage_change:.2f}%\\n\")\n",
      "\n",
      "# Fetch and display info for each ticker\n",
      "for ticker in tickers:\n",
      "    fetch_and_display_info(ticker)\n",
      "```\n",
      "\n",
      "Please save the above code in a file named `stock_info.py` and execute it. This script will output the current prices of NVDA and TSLA, along with the percentage changes in their stock prices over the past month.\n",
      "\n",
      "If you encounter any issues or have any questions regarding the execution or results, please let me know!\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[31m\n",
      ">>>>>>>> EXECUTING CODE BLOCK 0 (inferred language is python)...\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Researcher):\n",
      "\n",
      "exitcode: 0 (execution succeeded)\n",
      "Code output: \n",
      "NVDA Current Price: $726.13\n",
      "NVDA Performance Over The Past Month: 21.72%\n",
      "\n",
      "TSLA Current Price: $199.95\n",
      "TSLA Performance Over The Past Month: -4.24%\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mResearcher\u001b[0m (to User):\n",
      "\n",
      "The execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\n",
      "\n",
      "- **Nvidia Corporation (NVDA):**\n",
      "  - Current Price: $726.13\n",
      "  - Performance Over The Past Month: +21.72%\n",
      "\n",
      "- **Tesla, Inc. (TSLA):**\n",
      "  - Current Price: $199.95\n",
      "  - Performance Over The Past Month: -4.24%\n",
      "\n",
      "This data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\n",
      "\n",
      "These performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\n",
      "\n",
      "If you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "Investigate possible reasons of the stock performance.\n",
      "\n",
      "With the following carryover: \n",
      "The execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\n",
      "\n",
      "- **Nvidia Corporation (NVDA):**\n",
      "  - Current Price: $726.13\n",
      "  - Performance Over The Past Month: +21.72%\n",
      "\n",
      "- **Tesla, Inc. (TSLA):**\n",
      "  - Current Price: $199.95\n",
      "  - Performance Over The Past Month: -4.24%\n",
      "\n",
      "This data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\n",
      "\n",
      "These performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\n",
      "\n",
      "If you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\n",
      "\n",
      "\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Research_manager):\n",
      "\n",
      "Investigate possible reasons of the stock performance.\n",
      "Context: \n",
      "The execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\n",
      "\n",
      "- **Nvidia Corporation (NVDA):**\n",
      "  - Current Price: $726.13\n",
      "  - Performance Over The Past Month: +21.72%\n",
      "\n",
      "- **Tesla, Inc. (TSLA):**\n",
      "  - Current Price: $199.95\n",
      "  - Performance Over The Past Month: -4.24%\n",
      "\n",
      "This data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\n",
      "\n",
      "These performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\n",
      "\n",
      "If you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\n",
      "\n",
      "\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mResearcher\u001b[0m (to Research_manager):\n",
      "\n",
      "To investigate the possible reasons behind the stock performance of Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA), we need to consider various factors that could influence their stock prices. Here's a step-by-step plan for our investigation:\n",
      "\n",
      "1. **Market News and Events:** We will look for any recent news, announcements, or events related to Nvidia and Tesla that could influence investor sentiment and stock performance. This includes financial reports, product launches, regulatory changes, or significant partnerships.\n",
      "\n",
      "2. **Industry Trends:** The performance of a company's stock is also influenced by broader industry trends. For Nvidia, this might include the demand for GPUs for gaming, data centers, and AI applications. For Tesla, factors might include electric vehicle (EV) market trends, competition, and regulatory changes affecting the automotive industry.\n",
      "\n",
      "3. **Economic Indicators:** General economic conditions, such as interest rates, inflation, and consumer spending, can impact stock performance. A growing economy might fuel investments in technology and innovation, benefiting companies like Nvidia and Tesla.\n",
      "\n",
      "4. **Technological Innovations:** Any groundbreaking technological advancements announced by either company could affect stock prices. For Nvidia, this might be related to advancements in AI, while for Tesla, innovations in battery technology or autonomous driving could be significant.\n",
      "\n",
      "5. **Company-specific Factors:** Factors such as changes in leadership, legal issues, or supply chain disruptions could also impact the stock prices of Nvidia and Tesla.\n",
      "\n",
      "I will now search the web for the most recent news and information related to Nvidia (NVDA) and Tesla (TSLA) that could shed light on their recent stock performance. This will include looking into financial news, industry-related updates, and any recent announcements made by the companies themselves.\n",
      "\n",
      "```python\n",
      "# filename: fetch_news.py\n",
      "import requests\n",
      "from bs4 import BeautifulSoup\n",
      "\n",
      "def search_news(company):\n",
      "    # Searching for news on Google News\n",
      "    url = f'https://www.google.com/search?q={company}+stock+news&tbm=nws'\n",
      "    response = requests.get(url)\n",
      "    soup = BeautifulSoup(response.text, 'html.parser')\n",
      "    # Looking for headlines\n",
      "    headlines = soup.find_all('div', {'class': 'BVG0Nb'})\n",
      "    links = soup.find_all('a', href=True)\n",
      "    news_items = []\n",
      "    for headline, link in zip(headlines, links):\n",
      "        news_items.append({'title': headline.text, 'link': link['href']})\n",
      "    return news_items[:5]  # Returning the first 5 news items\n",
      "\n",
      "# Searching for news related to Nvidia and Tesla\n",
      "nvidia_news = search_news('Nvidia Corporation NVDA')\n",
      "tesla_news = search_news('Tesla Inc TSLA')\n",
      "\n",
      "# Printing out the news items\n",
      "print('Nvidia Corporation (NVDA) Recent News:')\n",
      "for news in nvidia_news:\n",
      "    print(f\"- {news['title']} {news['link']}\")\n",
      "\n",
      "print('\\nTesla, Inc. (TSLA) Recent News:')\n",
      "for news in tesla_news:\n",
      "    print(f\"- {news['title']} {news['link']}\")\n",
      "```\n",
      "\n",
      "Please execute the provided Python script to search for the latest news regarding Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). This will give us a starting point to understand the factors influencing their recent stock performance.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mCritic\u001b[0m (to Research_manager):\n",
      "\n",
      "The plan is logical and thorough, covering most essential factors that can affect the stock performance of Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are a few feedback points and suggestions to ensure a comprehensive investigation:\n",
      "\n",
      "1. **Execution Note:** Considering that the provided Python script uses web scraping to fetch the latest news from Google search results, it's important to note that this method might encounter challenges due to the dynamic nature of web content and potential anti-scraping measures. Users should ensure they are compliant with Google's Terms of Service and consider using official APIs for reliable data retrieval when possible.\n",
      "\n",
      "2. **Financial Performance:** While the plan mentions looking into general market news and events, it's specifically crucial to analyze the companies' latest financial reports (quarterly/annually). Insights into revenue, profit margins, growth forecasts, and analyst ratings could provide a more concrete basis for understanding stock performance.\n",
      "\n",
      "3. **Comparison with Competitors:** Adding a comparative analysis of competitors within the same industries (e.g., AMD for Nvidia and Ford or Rivian for Tesla) could offer additional context. Performance might not only be due to internal factors but also how these companies are doing relative to their peers.\n",
      "\n",
      "4. **Sentiment Analysis:** Analyzing investor sentiment, perhaps by looking at social media or investor forums, could give an idea of how market perceptions are influencing stock prices beyond just factual news.\n",
      "\n",
      "5. **Technological Roadmaps:** For companies like Nvidia and Tesla, where innovation is key, looking into their technology roadmaps or any patents they might have filed recently could provide insights into their future potential and how it's being valued by the market.\n",
      "\n",
      "6. **Environmental, Social, and Governance (ESG) Factors:** With increasing attention on sustainable investing, ESG factors might also play a role in a company's stock performance. For Tesla, environmental factors might be particularly relevant.\n",
      "\n",
      "7. **Source Verification:** The plan mentions that the executed Python script will fetch the most recent news for analysis. It’s important to cross-verify the information obtained from the news with reliable sources or directly from the company’s announcements to ensure accuracy.\n",
      "\n",
      "Following these suggestions, adjusting the plan for data reliability, and incorporating a broader analysis spectrum will likely yield a more comprehensive understanding of the stock performance for Nvidia and Tesla.\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[34mStart a new chat with the following message: \n",
      "Develop an engaging blog post using any information provided.\n",
      "\n",
      "With the following carryover: \n",
      "The execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\n",
      "\n",
      "- **Nvidia Corporation (NVDA):**\n",
      "  - Current Price: $726.13\n",
      "  - Performance Over The Past Month: +21.72%\n",
      "\n",
      "- **Tesla, Inc. (TSLA):**\n",
      "  - Current Price: $199.95\n",
      "  - Performance Over The Past Month: -4.24%\n",
      "\n",
      "This data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\n",
      "\n",
      "These performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\n",
      "\n",
      "If you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\n",
      "\n",
      "\n",
      "To investigate the stock performance of Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA), it's recommended to consider market news, industry trends, economic indicators, and company-specific factors including technological innovations. The plan includes executing a Python script to fetch the latest news. Feedback emphasizes ensuring compliance with Google's Terms of Service, analyzing financial reports, comparing competitors, sentiment analysis, investigating technological roadmaps, considering ESG factors, and verifying sources for accuracy. This comprehensive approach, adjusting for data reliability and a broader analysis spectrum, will aid in understanding the reasons behind the stock performance of Nvidia and Tesla.\u001b[0m\n",
      "\u001b[34m\n",
      "********************************************************************************\u001b[0m\n",
      "\u001b[33mUser\u001b[0m (to Writing_manager):\n",
      "\n",
      "Develop an engaging blog post using any information provided.\n",
      "Context: \n",
      "The execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\n",
      "\n",
      "- **Nvidia Corporation (NVDA):**\n",
      "  - Current Price: $726.13\n",
      "  - Performance Over The Past Month: +21.72%\n",
      "\n",
      "- **Tesla, Inc. (TSLA):**\n",
      "  - Current Price: $199.95\n",
      "  - Performance Over The Past Month: -4.24%\n",
      "\n",
      "This data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\n",
      "\n",
      "These performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\n",
      "\n",
      "If you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\n",
      "\n",
      "\n",
      "To investigate the stock performance of Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA), it's recommended to consider market news, industry trends, economic indicators, and company-specific factors including technological innovations. The plan includes executing a Python script to fetch the latest news. Feedback emphasizes ensuring compliance with Google's Terms of Service, analyzing financial reports, comparing competitors, sentiment analysis, investigating technological roadmaps, considering ESG factors, and verifying sources for accuracy. This comprehensive approach, adjusting for data reliability and a broader analysis spectrum, will aid in understanding the reasons behind the stock performance of Nvidia and Tesla.\n",
      "\n",
      "--------------------------------------------------------------------------------\n",
      "\u001b[33mWriter\u001b[0m (to Writing_manager):\n",
      "\n",
      "# Tech Titans in Turmoil? Deciphering the Divergent Paths of Nvidia and Tesla\n",
      "\n",
      "In the ever-dynamic world of technology stocks, recent market activities have drawn sharp attention to two behemoths: Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). With the execution of a specialized Python script, intriguing insights into their stock performances over the past month have emerged, revealing a fascinating divergence in their trajectory. Nvidia's stocks have surged, showcasing a robust growth of 21.72%, while Tesla has unexpectedly stumbled, recording a 4.24% decline in stock value. This unexpected dichotomy in the fortunes of two of Silicon Valley's most luminary companies offers a compelling case study into the undercurrents shaping the tech industry today.\n",
      "\n",
      "## The Surge of Nvidia: Riding the Wave of Innovation\n",
      "\n",
      "Nvidia's impressive stock performance, ballooning by 21.72%, paints a picture of a company at the zenith of its powers. The secret to Nvidia's success could largely be attributed to its strategic positioning at the heart of burgeoning tech trends, including AI, machine learning, and gaming. Nvidia's GPUs are not only the \"engine\" behind gaming PCs but are also crucial for AI research and data centers, industries that have seen exponential growth in recent years.\n",
      "\n",
      "Moreover, Nvidia's forward-looking approach and continuous innovation have cemented its status as a cornerstone in the tech space. Recent developments in AI and deep learning technologies, where Nvidia is a recognized leader, have further bolstered investor confidence. Their strategic partnerships and expansion into new, high-growth markets have likely contributed to their positive financial outlook, evident in the substantial stock price increase.\n",
      "\n",
      "## Tesla's Unanticipated Detour: A Bump in the Road?\n",
      "\n",
      "On the flip side, Tesla's slight retreat, with a 4.24% drop, poses intriguing questions about the underlying factors dampening investor enthusiasm. Tesla, under the visionary leadership of Elon Musk, has revolutionized the automotive industry, making electric vehicles (EVs) mainstream. Yet, even pioneers aren't immune to market forces and operational challenges.\n",
      "\n",
      "Analysts might speculate that Tesla's decline could be attributed to a variety of factors, including production delays, competition heating up from legacy automakers venturing into the EV space, and perhaps geopolitical tensions affecting supply chains. Additionally, the broader market's sentiment, influenced by economic indicators and shifts in consumer behavior, may have played a role in Tesla's recent stock performance downturn.\n",
      "\n",
      "## Beyond the Numbers: A Closer Look at the Forces at Play\n",
      "\n",
      "To truly comprehend the divergence in Nvidia's and Tesla's stock market performances, one must delve deeper beyond mere financial metrics. Exploring market news, industry trends, economic indicators, and company-specific dynamics offers richer context.\n",
      "\n",
      "For Nvidia, its stride might be bolstered by advancements in technology and a robust product line catering to future needs. For Tesla, despite its recent dip, the long-term outlook remains positive, given its pioneering status and relentless pursuit of innovation.\n",
      "\n",
      "Inherent in the analysis of stock performances is the necessity to consider technological roadmaps, environmental, social, and governance (ESG) factors, and competitive landscapes. These components, combined with meticulous sentiment analysis and a keen eye on financial reports, provide a multidimensional view of Nvidia's and Tesla's market positions.\n",
      "\n",
      "## Looking Ahead: Charting the Course\n",
      "\n",
      "As investors and enthusiasts keenly watch these unfolding narratives, the contrasting fortunes of Nvidia and Tesla underscore the volatile and unpredictable nature of the tech stock market. The journey ahead for both companies promises to be lined with opportunities and obstacles, making their stories not just a study of stock prices but a reflection of the broader technological and economic landscapes they operate within.\n",
      "\n",
      "Navigating this ever-evolving terrain requires a nuanced understanding of market dynamics, a commitment to innovation, and an unwavering focus on long-term value creation. As Nvidia and Tesla chart their paths forward, they not only shape their destinies but also the future of technology itself. Therefore, keeping a close watch on these titans' next moves becomes not just an interest but a necessity for those vested in the future of tech.\n",
      "\n",
      "In the interplay of market forces, innovation, and strategic visions, the contrasting trajectories of Nvidia and Tesla present a nuanced narrative, ripe for exploration and reflection. As we advance, their stories remind us of the transformative power of technology and the endless possibilities that lie within the volatile realm of the stock market.\n",
      "\n",
      "So, whether you're an investor, a tech enthusiast, or simply a curious observer, the unfolding saga of Nvidia and Tesla offers a captivating glimpse into the future of technology and finance, woven together in the complex tapestry of the stock market's highs and lows.\n",
      "\n",
      "---\n",
      "I hope you found this exploration into the fortunes of Nvidia and Tesla insightful and thought-provoking. Stay tuned for more analyses that bring the world of technology and finance to life in compelling narratives.\n",
      "\n",
      "TERMINATE\n",
      "\n",
      "--------------------------------------------------------------------------------\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "{1: ChatResult(chat_id=1, chat_history=[{'content': 'What are the current stock prices of NVDA and TESLA, and how is the performance over the past month in terms of percentage change?', 'role': 'assistant'}, {'content': 'To obtain the current stock prices of NVDA (Nvidia Corporation) and TSLA (Tesla, Inc.), as well as their performance over the past month in terms of percentage change, I will use Python code to fetch this information from a financial data API. For this task, we can use the Yahoo Finance API through the `yfinance` library, which allows us to collect stock information programmatically.\\n\\nHere is the plan:\\n1. Use Python code to access the required stock data via the `yfinance` library.\\n2. Fetch the current prices of NVDA and TSLA.\\n3. Calculate the percentage change in their stock prices over the past month.\\n\\nFirst, you\\'ll need to ensure that the `yfinance` library is installed. If it\\'s not already installed, you can install it using pip. Execute the following Python code to perform the tasks:\\n\\n```python\\n# filename: stock_info.py\\n\\nimport yfinance as yf\\nfrom datetime import datetime, timedelta\\n\\n# Define the tickers for Nvidia and Tesla\\ntickers = [\"NVDA\", \"TSLA\"]\\n\\n# Define the time period: end date is today, start date is one month ago\\nend_date = datetime.today()\\nstart_date = end_date - timedelta(days=30)\\n\\n# Function to fetch and display stock info\\ndef fetch_and_display_info(ticker):\\n    stock = yf.Ticker(ticker)\\n    \\n    # Fetch historical data for the past month\\n    hist = stock.history(start=start_date, end=end_date)\\n    \\n    # Get the last closing price (most recent date)\\n    last_close_price = hist[\\'Close\\'].iloc[-1]\\n    \\n    # Calculate the percentage change over the past month\\n    start_price = hist[\\'Close\\'].iloc[0]  # First day\\'s closing price in the hist data\\n    percentage_change = ((last_close_price - start_price) / start_price) * 100\\n    \\n    print(f\"{ticker} Current Price: ${last_close_price:.2f}\")\\n    print(f\"{ticker} Performance Over The Past Month: {percentage_change:.2f}%\\\\n\")\\n\\n# Fetch and display info for each ticker\\nfor ticker in tickers:\\n    fetch_and_display_info(ticker)\\n```\\n\\nPlease save the above code in a file named `stock_info.py` and execute it. This script will output the current prices of NVDA and TSLA, along with the percentage changes in their stock prices over the past month.\\n\\nIf you encounter any issues or have any questions regarding the execution or results, please let me know!', 'role': 'user'}, {'content': 'exitcode: 0 (execution succeeded)\\nCode output: \\nNVDA Current Price: $726.13\\nNVDA Performance Over The Past Month: 21.72%\\n\\nTSLA Current Price: $199.95\\nTSLA Performance Over The Past Month: -4.24%\\n\\n', 'role': 'assistant'}, {'content': \"The execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\\n\\n- **Nvidia Corporation (NVDA):**\\n  - Current Price: $726.13\\n  - Performance Over The Past Month: +21.72%\\n\\n- **Tesla, Inc. (TSLA):**\\n  - Current Price: $199.95\\n  - Performance Over The Past Month: -4.24%\\n\\nThis data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\\n\\nThese performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\\n\\nIf you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\\n\\nTERMINATE\", 'role': 'user'}], summary=\"The execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\\n\\n- **Nvidia Corporation (NVDA):**\\n  - Current Price: $726.13\\n  - Performance Over The Past Month: +21.72%\\n\\n- **Tesla, Inc. (TSLA):**\\n  - Current Price: $199.95\\n  - Performance Over The Past Month: -4.24%\\n\\nThis data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\\n\\nThese performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\\n\\nIf you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\\n\\n\", cost=({'total_cost': 0.038180000000000006, 'gpt-4-0125-preview': {'cost': 0.038180000000000006, 'prompt_tokens': 1592, 'completion_tokens': 742, 'total_tokens': 2334}}, {'total_cost': 0.038180000000000006, 'gpt-4-0125-preview': {'cost': 0.038180000000000006, 'prompt_tokens': 1592, 'completion_tokens': 742, 'total_tokens': 2334}}), human_input=[]),\n",
       " 2: ChatResult(chat_id=2, chat_history=[{'content': \"Investigate possible reasons of the stock performance.\\nContext: \\nThe execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\\n\\n- **Nvidia Corporation (NVDA):**\\n  - Current Price: $726.13\\n  - Performance Over The Past Month: +21.72%\\n\\n- **Tesla, Inc. (TSLA):**\\n  - Current Price: $199.95\\n  - Performance Over The Past Month: -4.24%\\n\\nThis data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\\n\\nThese performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\\n\\nIf you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\\n\\n\", 'role': 'assistant'}], summary=\"To investigate the stock performance of Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA), it's recommended to consider market news, industry trends, economic indicators, and company-specific factors including technological innovations. The plan includes executing a Python script to fetch the latest news. Feedback emphasizes ensuring compliance with Google's Terms of Service, analyzing financial reports, comparing competitors, sentiment analysis, investigating technological roadmaps, considering ESG factors, and verifying sources for accuracy. This comprehensive approach, adjusting for data reliability and a broader analysis spectrum, will aid in understanding the reasons behind the stock performance of Nvidia and Tesla.\", cost=({'total_cost': 0.03351, 'gpt-4-0125-preview': {'cost': 0.03351, 'prompt_tokens': 2970, 'completion_tokens': 127, 'total_tokens': 3097}}, {'total_cost': 0.03351, 'gpt-4-0125-preview': {'cost': 0.03351, 'prompt_tokens': 2970, 'completion_tokens': 127, 'total_tokens': 3097}}), human_input=[]),\n",
       " 3: ChatResult(chat_id=3, chat_history=[{'content': \"Develop an engaging blog post using any information provided.\\nContext: \\nThe execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\\n\\n- **Nvidia Corporation (NVDA):**\\n  - Current Price: $726.13\\n  - Performance Over The Past Month: +21.72%\\n\\n- **Tesla, Inc. (TSLA):**\\n  - Current Price: $199.95\\n  - Performance Over The Past Month: -4.24%\\n\\nThis data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\\n\\nThese performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\\n\\nIf you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\\n\\n\\nTo investigate the stock performance of Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA), it's recommended to consider market news, industry trends, economic indicators, and company-specific factors including technological innovations. The plan includes executing a Python script to fetch the latest news. Feedback emphasizes ensuring compliance with Google's Terms of Service, analyzing financial reports, comparing competitors, sentiment analysis, investigating technological roadmaps, considering ESG factors, and verifying sources for accuracy. This comprehensive approach, adjusting for data reliability and a broader analysis spectrum, will aid in understanding the reasons behind the stock performance of Nvidia and Tesla.\", 'role': 'assistant'}], summary=\"Develop an engaging blog post using any information provided.\\nContext: \\nThe execution of the provided Python code successfully fetched the current stock prices and the performance over the past month for Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA). Here are the results:\\n\\n- **Nvidia Corporation (NVDA):**\\n  - Current Price: $726.13\\n  - Performance Over The Past Month: +21.72%\\n\\n- **Tesla, Inc. (TSLA):**\\n  - Current Price: $199.95\\n  - Performance Over The Past Month: -4.24%\\n\\nThis data indicates that over the past month, NVDA's stock has seen a significant positive increase in its price, with a 21.72% rise, showcasing strong performance. On the other hand, TSLA's stock has experienced a slight decline, with a 4.24% decrease in its price.\\n\\nThese performance metrics can be useful for investors and traders to understand recent trends in these companies' stock values.\\n\\nIf you have any more questions or need further assistance, feel free to ask. Otherwise, we can conclude here.\\n\\n\\nTo investigate the stock performance of Nvidia Corporation (NVDA) and Tesla, Inc. (TSLA), it's recommended to consider market news, industry trends, economic indicators, and company-specific factors including technological innovations. The plan includes executing a Python script to fetch the latest news. Feedback emphasizes ensuring compliance with Google's Terms of Service, analyzing financial reports, comparing competitors, sentiment analysis, investigating technological roadmaps, considering ESG factors, and verifying sources for accuracy. This comprehensive approach, adjusting for data reliability and a broader analysis spectrum, will aid in understanding the reasons behind the stock performance of Nvidia and Tesla.\", cost=({'total_cost': 0.0058200000000000005, 'gpt-4-0125-preview': {'cost': 0.0058200000000000005, 'prompt_tokens': 579, 'completion_tokens': 1, 'total_tokens': 580}}, {'total_cost': 0.0058200000000000005, 'gpt-4-0125-preview': {'cost': 0.0058200000000000005, 'prompt_tokens': 579, 'completion_tokens': 1, 'total_tokens': 580}}), human_input=[])}"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "user_proxy = autogen.UserProxyAgent(\n",
    "    name=\"User_proxy\",\n",
    "    system_message=\"A human admin.\",\n",
    "    human_input_mode=\"NEVER\",\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
    "    code_execution_config={\n",
    "        \"last_n_messages\": 1,\n",
    "        \"work_dir\": \"groupchat\",\n",
    "        \"use_docker\": False,\n",
    "    },\n",
    ")\n",
    "\n",
    "research_assistant = autogen.AssistantAgent(\n",
    "    name=\"Researcher\",\n",
    "    llm_config={\"config_list\": config_list},\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\") and x.get(\"content\", \"\").rstrip().endswith(\"TERMINATE\"),\n",
    ")\n",
    "\n",
    "writer = autogen.AssistantAgent(\n",
    "    name=\"Writer\",\n",
    "    llm_config={\"config_list\": config_list},\n",
    "    system_message=\"\"\"\n",
    "    You are a professional writer, known for\n",
    "    your insightful and engaging articles.\n",
    "    You transform complex concepts into compelling narratives.\n",
    "    Reply \"TERMINATE\" in the end when everything is done.\n",
    "    \"\"\",\n",
    ")\n",
    "\n",
    "critic = autogen.AssistantAgent(\n",
    "    name=\"Critic\",\n",
    "    system_message=\"\"\"Critic. Double check plan, claims, code from other agents and provide feedback. Check whether the plan includes adding verifiable info such as source URL.\n",
    "    Reply \"TERMINATE\" in the end when everything is done.\n",
    "    \"\"\",\n",
    "    llm_config={\"config_list\": config_list},\n",
    ")\n",
    "\n",
    "groupchat_1 = autogen.GroupChat(agents=[user_proxy, research_assistant, critic], messages=[], max_round=50)\n",
    "\n",
    "groupchat_2 = autogen.GroupChat(agents=[user_proxy, writer, critic], messages=[], max_round=50)\n",
    "\n",
    "manager_1 = autogen.GroupChatManager(\n",
    "    groupchat=groupchat_1,\n",
    "    name=\"Research_manager\",\n",
    "    llm_config={\"config_list\": config_list},\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\").find(\"TERMINATE\") >= 0,\n",
    "    code_execution_config={\n",
    "        \"last_n_messages\": 1,\n",
    "        \"work_dir\": \"groupchat\",\n",
    "        \"use_docker\": False,\n",
    "    },\n",
    ")\n",
    "manager_2 = autogen.GroupChatManager(\n",
    "    groupchat=groupchat_2,\n",
    "    name=\"Writing_manager\",\n",
    "    llm_config={\"config_list\": config_list},\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\").find(\"TERMINATE\") >= 0,\n",
    "    code_execution_config={\n",
    "        \"last_n_messages\": 1,\n",
    "        \"work_dir\": \"groupchat\",\n",
    "        \"use_docker\": False,\n",
    "    },\n",
    ")\n",
    "\n",
    "user = autogen.UserProxyAgent(\n",
    "    name=\"User\",\n",
    "    human_input_mode=\"NEVER\",\n",
    "    is_termination_msg=lambda x: x.get(\"content\", \"\").find(\"TERMINATE\") >= 0,\n",
    "    code_execution_config={\n",
    "        \"last_n_messages\": 1,\n",
    "        \"work_dir\": \"tasks\",\n",
    "        \"use_docker\": False,\n",
    "    },  # Please set use_docker=True if docker is available to run the generated code. Using docker is safer than running the generated code directly.\n",
    ")\n",
    "await user.a_initiate_chats(  # noqa: F704\n",
    "    [\n",
    "        {\"chat_id\": 1, \"recipient\": research_assistant, \"message\": financial_tasks[0], \"summary_method\": \"last_msg\"},\n",
    "        {\n",
    "            \"chat_id\": 2,\n",
    "            \"prerequisites\": [1],\n",
    "            \"recipient\": manager_1,\n",
    "            \"message\": financial_tasks[1],\n",
    "            \"summary_method\": \"reflection_with_llm\",\n",
    "        },\n",
    "        {\n",
    "            \"chat_id\": 3,\n",
    "            \"prerequisites\": [1],\n",
    "            \"recipient\": manager_1,\n",
    "            \"message\": financial_tasks[2],\n",
    "            \"summary_method\": \"reflection_with_llm\",\n",
    "        },\n",
    "        {\"chat_id\": 4, \"prerequisites\": [1, 2, 3], \"recipient\": manager_2, \"message\": writing_tasks[0]},\n",
    "    ]\n",
    ")"
   ]
  }
 ],
 "metadata": {
  "front_matter": {
    "tags": ["sequential chat"],
    "description": "Use conversational agents to solve a set of tasks with a sequence of async chats."
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.7"
  },
  "vscode": {
   "interpreter": {
    "hash": "949777d72b0d2535278d3dc13498b2535136f6dfe0678499012e853ee9abcab1"
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {
     "2d910cfd2d2a4fc49fc30fbbdc5576a7": {
      "model_module": "@jupyter-widgets/base",
      "model_module_version": "2.0.0",
      "model_name": "LayoutModel",
      "state": {
       "_model_module": "@jupyter-widgets/base",
       "_model_module_version": "2.0.0",
       "_model_name": "LayoutModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/base",
       "_view_module_version": "2.0.0",
       "_view_name": "LayoutView",
       "align_content": null,
       "align_items": null,
       "align_self": null,
       "border_bottom": null,
       "border_left": null,
       "border_right": null,
       "border_top": null,
       "bottom": null,
       "display": null,
       "flex": null,
       "flex_flow": null,
       "grid_area": null,
       "grid_auto_columns": null,
       "grid_auto_flow": null,
       "grid_auto_rows": null,
       "grid_column": null,
       "grid_gap": null,
       "grid_row": null,
       "grid_template_areas": null,
       "grid_template_columns": null,
       "grid_template_rows": null,
       "height": null,
       "justify_content": null,
       "justify_items": null,
       "left": null,
       "margin": null,
       "max_height": null,
       "max_width": null,
       "min_height": null,
       "min_width": null,
       "object_fit": null,
       "object_position": null,
       "order": null,
       "overflow": null,
       "padding": null,
       "right": null,
       "top": null,
       "visibility": null,
       "width": null
      }
     },
     "454146d0f7224f038689031002906e6f": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "2.0.0",
      "model_name": "HBoxModel",
      "state": {
       "_dom_classes": [],
       "_model_module": "@jupyter-widgets/controls",
       "_model_module_version": "2.0.0",
       "_model_name": "HBoxModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/controls",
       "_view_module_version": "2.0.0",
       "_view_name": "HBoxView",
       "box_style": "",
       "children": [
        "IPY_MODEL_e4ae2b6f5a974fd4bafb6abb9d12ff26",
        "IPY_MODEL_577e1e3cc4db4942b0883577b3b52755",
        "IPY_MODEL_b40bdfb1ac1d4cffb7cefcb870c64d45"
       ],
       "layout": "IPY_MODEL_dc83c7bff2f241309537a8119dfc7555",
       "tabbable": null,
       "tooltip": null
      }
     },
     "577e1e3cc4db4942b0883577b3b52755": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "2.0.0",
      "model_name": "FloatProgressModel",
      "state": {
       "_dom_classes": [],
       "_model_module": "@jupyter-widgets/controls",
       "_model_module_version": "2.0.0",
       "_model_name": "FloatProgressModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/controls",
       "_view_module_version": "2.0.0",
       "_view_name": "ProgressView",
       "bar_style": "success",
       "description": "",
       "description_allow_html": false,
       "layout": "IPY_MODEL_2d910cfd2d2a4fc49fc30fbbdc5576a7",
       "max": 1,
       "min": 0,
       "orientation": "horizontal",
       "style": "IPY_MODEL_74a6ba0c3cbc4051be0a83e152fe1e62",
       "tabbable": null,
       "tooltip": null,
       "value": 1
      }
     },
     "6086462a12d54bafa59d3c4566f06cb2": {
      "model_module": "@jupyter-widgets/base",
      "model_module_version": "2.0.0",
      "model_name": "LayoutModel",
      "state": {
       "_model_module": "@jupyter-widgets/base",
       "_model_module_version": "2.0.0",
       "_model_name": "LayoutModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/base",
       "_view_module_version": "2.0.0",
       "_view_name": "LayoutView",
       "align_content": null,
       "align_items": null,
       "align_self": null,
       "border_bottom": null,
       "border_left": null,
       "border_right": null,
       "border_top": null,
       "bottom": null,
       "display": null,
       "flex": null,
       "flex_flow": null,
       "grid_area": null,
       "grid_auto_columns": null,
       "grid_auto_flow": null,
       "grid_auto_rows": null,
       "grid_column": null,
       "grid_gap": null,
       "grid_row": null,
       "grid_template_areas": null,
       "grid_template_columns": null,
       "grid_template_rows": null,
       "height": null,
       "justify_content": null,
       "justify_items": null,
       "left": null,
       "margin": null,
       "max_height": null,
       "max_width": null,
       "min_height": null,
       "min_width": null,
       "object_fit": null,
       "object_position": null,
       "order": null,
       "overflow": null,
       "padding": null,
       "right": null,
       "top": null,
       "visibility": null,
       "width": null
      }
     },
     "74a6ba0c3cbc4051be0a83e152fe1e62": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "2.0.0",
      "model_name": "ProgressStyleModel",
      "state": {
       "_model_module": "@jupyter-widgets/controls",
       "_model_module_version": "2.0.0",
       "_model_name": "ProgressStyleModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/base",
       "_view_module_version": "2.0.0",
       "_view_name": "StyleView",
       "bar_color": null,
       "description_width": ""
      }
     },
     "7d3f3d9e15894d05a4d188ff4f466554": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "2.0.0",
      "model_name": "HTMLStyleModel",
      "state": {
       "_model_module": "@jupyter-widgets/controls",
       "_model_module_version": "2.0.0",
       "_model_name": "HTMLStyleModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/base",
       "_view_module_version": "2.0.0",
       "_view_name": "StyleView",
       "background": null,
       "description_width": "",
       "font_size": null,
       "text_color": null
      }
     },
     "b40bdfb1ac1d4cffb7cefcb870c64d45": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "2.0.0",
      "model_name": "HTMLModel",
      "state": {
       "_dom_classes": [],
       "_model_module": "@jupyter-widgets/controls",
       "_model_module_version": "2.0.0",
       "_model_name": "HTMLModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/controls",
       "_view_module_version": "2.0.0",
       "_view_name": "HTMLView",
       "description": "",
       "description_allow_html": false,
       "layout": "IPY_MODEL_f1355871cc6f4dd4b50d9df5af20e5c8",
       "placeholder": "​",
       "style": "IPY_MODEL_ca245376fd9f4354af6b2befe4af4466",
       "tabbable": null,
       "tooltip": null,
       "value": " 1/1 [00:00&lt;00:00, 44.69it/s]"
      }
     },
     "ca245376fd9f4354af6b2befe4af4466": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "2.0.0",
      "model_name": "HTMLStyleModel",
      "state": {
       "_model_module": "@jupyter-widgets/controls",
       "_model_module_version": "2.0.0",
       "_model_name": "HTMLStyleModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/base",
       "_view_module_version": "2.0.0",
       "_view_name": "StyleView",
       "background": null,
       "description_width": "",
       "font_size": null,
       "text_color": null
      }
     },
     "dc83c7bff2f241309537a8119dfc7555": {
      "model_module": "@jupyter-widgets/base",
      "model_module_version": "2.0.0",
      "model_name": "LayoutModel",
      "state": {
       "_model_module": "@jupyter-widgets/base",
       "_model_module_version": "2.0.0",
       "_model_name": "LayoutModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/base",
       "_view_module_version": "2.0.0",
       "_view_name": "LayoutView",
       "align_content": null,
       "align_items": null,
       "align_self": null,
       "border_bottom": null,
       "border_left": null,
       "border_right": null,
       "border_top": null,
       "bottom": null,
       "display": null,
       "flex": null,
       "flex_flow": null,
       "grid_area": null,
       "grid_auto_columns": null,
       "grid_auto_flow": null,
       "grid_auto_rows": null,
       "grid_column": null,
       "grid_gap": null,
       "grid_row": null,
       "grid_template_areas": null,
       "grid_template_columns": null,
       "grid_template_rows": null,
       "height": null,
       "justify_content": null,
       "justify_items": null,
       "left": null,
       "margin": null,
       "max_height": null,
       "max_width": null,
       "min_height": null,
       "min_width": null,
       "object_fit": null,
       "object_position": null,
       "order": null,
       "overflow": null,
       "padding": null,
       "right": null,
       "top": null,
       "visibility": null,
       "width": null
      }
     },
     "e4ae2b6f5a974fd4bafb6abb9d12ff26": {
      "model_module": "@jupyter-widgets/controls",
      "model_module_version": "2.0.0",
      "model_name": "HTMLModel",
      "state": {
       "_dom_classes": [],
       "_model_module": "@jupyter-widgets/controls",
       "_model_module_version": "2.0.0",
       "_model_name": "HTMLModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/controls",
       "_view_module_version": "2.0.0",
       "_view_name": "HTMLView",
       "description": "",
       "description_allow_html": false,
       "layout": "IPY_MODEL_6086462a12d54bafa59d3c4566f06cb2",
       "placeholder": "​",
       "style": "IPY_MODEL_7d3f3d9e15894d05a4d188ff4f466554",
       "tabbable": null,
       "tooltip": null,
       "value": "100%"
      }
     },
     "f1355871cc6f4dd4b50d9df5af20e5c8": {
      "model_module": "@jupyter-widgets/base",
      "model_module_version": "2.0.0",
      "model_name": "LayoutModel",
      "state": {
       "_model_module": "@jupyter-widgets/base",
       "_model_module_version": "2.0.0",
       "_model_name": "LayoutModel",
       "_view_count": null,
       "_view_module": "@jupyter-widgets/base",
       "_view_module_version": "2.0.0",
       "_view_name": "LayoutView",
       "align_content": null,
       "align_items": null,
       "align_self": null,
       "border_bottom": null,
       "border_left": null,
       "border_right": null,
       "border_top": null,
       "bottom": null,
       "display": null,
       "flex": null,
       "flex_flow": null,
       "grid_area": null,
       "grid_auto_columns": null,
       "grid_auto_flow": null,
       "grid_auto_rows": null,
       "grid_column": null,
       "grid_gap": null,
       "grid_row": null,
       "grid_template_areas": null,
       "grid_template_columns": null,
       "grid_template_rows": null,
       "height": null,
       "justify_content": null,
       "justify_items": null,
       "left": null,
       "margin": null,
       "max_height": null,
       "max_width": null,
       "min_height": null,
       "min_width": null,
       "object_fit": null,
       "object_position": null,
       "order": null,
       "overflow": null,
       "padding": null,
       "right": null,
       "top": null,
       "visibility": null,
       "width": null
      }
     }
    },
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
